package com.bingo.lenovo.ttmusic;


import android.media.MediaPlayer;
import android.os.Environment;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建一个播放器的Service的类，
 * Created by lenovo on 2016/3/22.
 */

public class MusicService {
    //1.声明以下对象
    private static final File MUSIC_PATH = Environment
            .getExternalStorageDirectory();//找到Music存放的路径
    public List<String> musicList;//存放找到的所有MP3的绝对路径
    public MediaPlayer player;//定义多媒体对象
    public int songNum;//d当前播放的歌曲在List中的下标
    public String songName;//当前播放的歌曲名

    //2.加载刚才添加的MP3文件
    class MusicFilter implements FilenameFilter {
        public boolean accept(File dir, String name) {
            return (name.endsWith(".mp3"));
        }
    }
    //3.实例化MusicService的无参构造函数的对象，并把这些MP3文件放到musicList中
    public MusicService() {
        musicList = new ArrayList<String>();
        player = new MediaPlayer();

        if (MUSIC_PATH.listFiles(new MusicFilter()).length > 0) {
            for (File file : MUSIC_PATH.listFiles(new MusicFilter())) {
                musicList.add(file.getAbsolutePath());
            }
        }
    }

    //4.设置当前播放歌曲的名字
    public void setPlayName(String dataSource) {
        File file = new File(dataSource);
        String name = file.getName();//name=mm.mp3
        int index = name.lastIndexOf(".");//找到一个最后一个
        songName = name.substring(0,index);//截取为mm
    }
    //5.声明基本方法 开始、暂停、停止、上一首、下一首。
    public void start(){
        try {
            player.reset();//重置多媒体
            String dataSource = musicList.get(songNum);//得到当前播放音乐路径
            setPlayName(dataSource);//截取歌名
            player.setDataSource(dataSource);//为多媒体设置播放的路径
            player.prepare();//准备播放
            player.start();//开始播放
            //setOnCompletionListener当前多媒体播放完成时发生的事件
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer arg) {
                    next();//如果当前播放完毕，自动播放下一首
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void next(){
        songNum = songNum ==musicList.size()-1?0:songNum+1;
        start();
    }
    public void last(){
        songNum = songNum ==musicList.size()-1?0:songNum+1;
        start();
    }
    public void pasue(){
            if(player.isPlaying()){
                player.pause();
            }else {
                player.start();
            }
    }
    public void stop() {
        if (player.isPlaying()) {
            player.stop();
        }
    }
}
